package bitter.jnibridge;

import java.lang.reflect.*;

public class JNIBridge {
    static native void delete(final long p0);

    static void disableInterfaceProxy(final Object o) {
        ((a) Proxy.getInvocationHandler(o)).a();
    }

    static native Object invoke(final long p0, final Class p1, final Method p2, final Object[] p3);

    static Object newInterfaceProxy(final long n, final Class[] array) {
        return Proxy.newProxyInstance(JNIBridge.class.getClassLoader(), array, new a(n));
    }

    private static final class a implements InvocationHandler {
        private Object a;
        private long b;

        public a(final long b) {
            this.a = new Object[0];
            this.b = b;
        }

        public final void a() {
            synchronized (this.a) {
                this.b = 0L;
            }
        }

        public final void finalize() {
            synchronized (this.a) {
                if (this.b == 0L) {
                    return;
                }
                JNIBridge.delete(this.b);
            }
        }

        @Override
        public final Object invoke(final Object o, final Method method, final Object[] array) {
            synchronized (this.a) {
                if (this.b == 0L) {
                    return null;
                }
                return JNIBridge.invoke(this.b, method.getDeclaringClass(), method, array);
            }
        }
    }
}
